package com.my.javaweb;

import com.my.frame.pojo.Message;
import com.my.frame.pojo.User;
import com.my.frame.service.IMsgService;
import com.my.frame.service.IUserService;
import com.my.frame.service.impl.MsgServiceImpl;
import com.my.frame.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutionException;

@WebServlet(name = "MessageDemo" ,urlPatterns = "/message")
public class MessageDemo extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");//设置请求编码格式
        resp.setContentType("text/html;charset=utf-8");//设置响应编码格式

        //获取请求信息

        User u = (User)req.getSession().getAttribute("user");
        String msg = req.getParameter("msg");
        IMsgService ms = new MsgServiceImpl();
        //处理请求
        if(msg != ""){
            try {
                ms.addMsg(msg,u.getId());///空指针异常
            }catch (NullPointerException e){
                e.printStackTrace();
            }
        }

        //显示
        if(ms.getAllMsg()!=null){
            List<Message> msgs = ms.getAllMsg();
            IUserService us = new UserServiceImpl();
            for (Message message:msgs) {
                u =  us.checklogin(message.getUid());
                resp.getWriter().write(message.getMsg()+"<br/>"+"-----"+u.getName()+"<br/>");
            }
        }
        else
            resp.getWriter().write("没有留言");
    }
}
